package com.baizhi.controller;

import com.baizhi.common.Constant;
import com.baizhi.entity.Manager;
import com.baizhi.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("manager")
public class ManagerController {
    private ManagerService managerService;
    @Autowired
    public void setManagerService(ManagerService managerService) {
        this.managerService = managerService;
    }
    @RequestMapping("login")
    public String login(String username, String password, HttpSession session){
        boolean login = managerService.login(username, password);
        if(login){
            Manager manager = managerService.selectByName(username);
            session.setAttribute("login",manager);
            return "redirect:/department/showDepartment";
        }else{
            return "login";
        }
    }
    @RequestMapping("exit")
    public String exit(HttpSession session){
        session.removeAttribute("login");
        return "login";
    }

    @RequestMapping("regist")
    public String regist(Manager manager, MultipartFile cover) throws IOException {
        String coverName = cover.getOriginalFilename();//上传头像的原文件名字
        String fileName = UUID.randomUUID().toString()+coverName;//上传后保存到数据库的名字
        cover.transferTo(new File(Constant.IMG_LOCATION,fileName));
        //调用业务层添加方法前  先将上传后的头像名保存到对象中
        manager.setPic(fileName);
        int i = managerService.insertManager(manager);
        if(i>0){
            return "index";
        }else{
            return "regist";
        }
    }
}
